package com.hm.ibsm.util;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import com.hm.common.util.CommonUtil;

/**
 * @author shishun.wang
 * @date 2017年2月22日 下午4:12:06
 * @version 1.0
 * @param <T>
 * @describe
 */
@SuppressWarnings("unchecked")
public class RedisObjectSerializer<T> implements RedisSerializer<T> {

	private Converter<Object, byte[]> serializer = new SerializingConverter();

	private Converter<byte[], Object> deserializer = new DeserializingConverter();

	static final byte[] EMPTY_ARRAY = new byte[0];

	@Override
	public T deserialize(byte[] bytes) throws SerializationException {
		if (CommonUtil.isEmpty(bytes)) {
			return null;
		}
		try {
			return (T) deserializer.convert(bytes);
		} catch (Exception ex) {
			throw new SerializationException("Cannot deserialize", ex);
		}
	}

	@Override
	public byte[] serialize(T entity) throws SerializationException {
		if (CommonUtil.isEmpty(entity)) {
			return EMPTY_ARRAY;
		}
		try {
			return serializer.convert(entity);
		} catch (Exception ex) {
			return EMPTY_ARRAY;
		}
	}

}
